
package de.unihannover.se.restlab.microblog.data;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import de.unihannover.se.restlab.microblog.models.Account;
import de.unihannover.se.restlab.microblog.models.Role;
import de.unihannover.se.restlab.microblog.models.User;


/*
 * 
 * TODO: FIXME: Allgemein mal so:
 * Sollten die Storages nicht am Anfang aus der Datenbank mit Entities gefüllt
 * werden so ka über em.find bis nix drin ist oder eine select * query.
 * 
 * Wie wird die Abbildung und das Synchronisieren von JAX und JPA Objekten 
 * gehandelt?
 * 
 */

/** A List of Accounts
 * @author restlab_c */
@Stateless
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class AccountStorage extends AbstractStorage {

	public static AccountStorage getStorage () {
		return (AccountStorage)getConcreteStorage(AccountStorage.class);
	}

	@PersistenceContext
	private EntityManager em;

	@XmlElement(name = "account")
	private List<Account> accounts = new ArrayList<Account>();

	public Account createAccount (User u, Role r, String password) {
		Account account = new Account(u, r, password);
		accounts.add(account);
		
		//em.persist(account);
		//em.getTransaction().commit();
		//em.close();
		
		em.persist(new de.unihannover.se.restlab.microblog.jpamodels.Account(account));
		
		return account;
	}

	public Account createAccount (User u, Role r) {
		Account account = new Account(u, r);
		accounts.add(account);

		//em.persist(account);
		//em.getTransaction().commit();
		//em.close();

		return account;
	}

	public List<Account> getAccounts () {
		return accounts;
	}

	public Account getAccount (Integer id) {
		// What was that for?
		// return (id < accounts.size() + 1) ? accounts.get(id-1000) : null;

		return (id < accounts.size()) ? accounts.get(id) : null;
	}

	public Account getAccount (String userName) {
		for (Account acc : accounts) {
			if (acc.getUser().getName().equals(userName)) {
				return acc;
			}
		}
		System.out.println("Kein Account zu " + userName + " gefunden!");
		return null;
	}

	public void removeAccount (Account account) {
		//em.remove(account);
		//em.getTransaction().commit();
		//em.close();
		accounts.remove(account.getPersistence());
	}

	public void clear () {
		setup();
		for(Account a : accounts) {
			em.remove(a.getPersistence());
		}
		accounts.clear();
	}

	public void setup () {
		int i = 1;
		while(true) {
			de.unihannover.se.restlab.microblog.jpamodels.Account a = em.find(de.unihannover.se.restlab.microblog.jpamodels.Account.class, i++);
			if(a == null) break;
			accounts.add(new Account(a));
		}
	}

}
